package com.xincheng.library.mvp.model;

import com.xincheng.library.mvp.listener.BaseModelListener;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by xiaote on 2016/11/1.
 */

public abstract class MvpModel<E, T> implements BaseModel<E, T> {
    private Disposable mDisposable;
    private BaseModelListener listener;

    public MvpModel() {

    }

    public abstract Observable<T> createObservable(E e);

    @Override
    public Disposable getData(int code, E e, BaseModelListener<T> listener) {
        Observable<T> observable = createObservable(e);
        this.listener = listener;
        return toSubscriber(observable, code, listener);
    }

    private Disposable toSubscriber(Observable<T> observable, final int code, final BaseModelListener<T> listener) {
        listener.onStart(code);
        return observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io()) //在io线程中处理网络请求
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<T>() {
                    @Override
                    public void accept(T t) throws Exception {
                        if(listener != null) {
                            listener.onSuccess(code, t);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if(listener != null) {
                            listener.onFinish(code);
                            listener.onFailed(code, throwable.getMessage());
                        }
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        if(listener != null) {
                            listener.onFinish(code);
                        }
                    }
                }, new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mDisposable = disposable;
                    }
                });
    }

    public void unSubscriber() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        if(listener != null) {
            listener = null;
        }
    }

}
